java implementation of pdf file screenshot method [PDFRenderer. jar download]

  • 2020-12-20 03:33:16
  • OfStack

This article illustrates how java implements pdf file screenshots. To share for your reference, the details are as follows:

In the latest website, there is a requirement to upload pdf file and display the cover page of pdf. Click the cover page and then read it online. Here, PDFRender is used to take screenshots of pdf.


public static boolean createScreenShoot(String source, String target) {
    File file = new File(source);
    if (!file.exists()) {
      System.err.println(" The path [" + source + "] The corresponding pdf File does not exist !");
      return false;
    }
    try{
      RandomAccessFile raf = new RandomAccessFile(file, "r");
      FileChannel channel = raf.getChannel();
      ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
      PDFFile pdffile = new PDFFile(buf);
      int num = pdffile.getNumPages();
      for(int i = 1; i < num; i++){
         PDFPage page = pdffile.getPage(1);
          // get the width and height for the doc at the default zoom
          Rectangle rect = new Rectangle(0, 0, (int) page.getBBox()
              .getWidth(), (int) page.getBBox().getHeight());
          // generate the image
          Image img = page.getImage(rect.width, rect.height, // width &
              rect, // clip rect
              null, // null for the ImageObserver
              true, // fill background with white
              true // block until drawing is done
              );
          BufferedImage tag = new BufferedImage(rect.width, rect.height,   BufferedImage.TYPE_INT_RGB);
          tag.getGraphics().drawImage(img, 0, 0, rect.width, rect.height,null);
          FileOutputStream out = new FileOutputStream(target+i+"jpg");
          JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
          encoder.encode(tag); // JPEG coding 
          out.close();
      }
      return true;
    }catch(Exception e){
      e.printStackTrace();
       return true;
    }

Also, if you want to display pdf online, you need to set the response header


response.setContentType("application/pdf");

pdfRender.jar click here to download.

For more java related content, readers can check out Java image manipulation Skills summary, java Date and Time manipulation skills Summary, Java DOM Node Manipulation Skills Summary, Java File and directory manipulation Skills Summary and Java Data Structure and Algorithm Tutorial.

I hope this article has been helpful for java programming.


Related articles: